import { Injectable, PLATFORM_ID, Inject } from '@angular/core';
import { Observable, of } from 'rxjs';
import { tap } from 'rxjs/operators';
import { isPlatformBrowser } from '@angular/common';

export interface LoginCredentials {
  username: string;
  password: string;
}

export interface LoginResponse {
  token: string;
  user: {
    id: number;
    username: string;
  };
}

@Injectable({
  providedIn: 'root'
})
export class LoginService {
  private readonly TOKEN_KEY = 'auth_token';
  private readonly USERNAME_KEY = 'username';
  private readonly USERS_KEY = 'registered_users';
  private isBrowser: boolean;

  constructor(@Inject(PLATFORM_ID) platformId: Object) {
    this.isBrowser = isPlatformBrowser(platformId);
  }

  register(credentials: LoginCredentials): Observable<void> {
    return new Observable(subscriber => {
      if (!this.isBrowser) {
        subscriber.error(new Error('注册功能在服务器端不可用'));
        return;
      }

      const users = this.getRegisteredUsers();
      
      // 检查用户名是否已存在
      if (users.some(user => user.username === credentials.username)) {
        subscriber.error(new Error('用户名已存在'));
        return;
      }

      // 保存新用户
      users.push({
        username: credentials.username,
        password: credentials.password // 实际应用中应该加密存储
      });
      localStorage.setItem(this.USERS_KEY, JSON.stringify(users));
      
      subscriber.next();
      subscriber.complete();
    });
  }

  login(credentials: LoginCredentials): Observable<LoginResponse> {
    return new Observable(subscriber => {
      if (!this.isBrowser) {
        subscriber.error(new Error('登录功能在服务器端不可用'));
        return;
      }

      const users = this.getRegisteredUsers();
      const user = users.find(u => 
        u.username === credentials.username && 
        u.password === credentials.password
      );

      if (!user) {
        subscriber.error(new Error('用户名或密码错误'));
        return;
      }

      const response: LoginResponse = {
        token: 'mock_token_' + Date.now(),
        user: {
          id: users.indexOf(user) + 1,
          username: user.username
        }
      };

      this.setToken(response.token);
      this.setUsername(response.user.username);
      
      subscriber.next(response);
      subscriber.complete();
    });
  }

  logout(): void {
    if (this.isBrowser) {
      localStorage.removeItem(this.TOKEN_KEY);
      localStorage.removeItem(this.USERNAME_KEY);
    }
  }

  isLoggedIn(): boolean {
    return !!this.getToken();
  }

  getToken(): string | null {
    if (this.isBrowser) {
      return localStorage.getItem(this.TOKEN_KEY);
    }
    return null;
  }

  getUsername(): string {
    if (this.isBrowser) {
      return localStorage.getItem(this.USERNAME_KEY) || 'Guest';
    }
    return 'Guest';
  }

  private setToken(token: string): void {
    if (this.isBrowser) {
      localStorage.setItem(this.TOKEN_KEY, token);
    }
  }

  private setUsername(username: string): void {
    if (this.isBrowser) {
      localStorage.setItem(this.USERNAME_KEY, username);
    }
  }

  private getRegisteredUsers(): Array<{username: string; password: string}> {
    if (!this.isBrowser) {
      return [];
    }
    const usersJson = localStorage.getItem(this.USERS_KEY);
    return usersJson ? JSON.parse(usersJson) : [];
  }
}